package com.ysm.smfu.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 版权所有 违法必究
 */
public class PinYinUtils {
    public static String getPinYin(String text) {
        char[] chars = text.toCharArray();
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        //声调
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//取消声调
        outputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//大写
        StringBuilder stringBuilder = new StringBuilder();
        for (char ch : chars) {
            if (Character.isWhitespace(ch)) {
                continue;//跳过当前循环 ,进入下次循环
            }

            if (ch > 128 || ch < -127) {// 是中文
                try {
                    // 贾平凹 多音字
                    String[] array = PinyinHelper.toHanyuPinyinStringArray(ch, outputFormat);
                    if (stringBuilder != null && array != null && array[0] != null)
                        stringBuilder.append(array[0]);
                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }
}
